﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Publicuse.DBCore.Redis.CMultiplexer
{
    /// <summary>
    ///  Redis管理中心
    /// </summary>
    public sealed class CMultiplexerManager
    {
        /// <summary>
        /// Redis客户端池化管理
        /// </summary>
        private static Dictionary<int, ConnectionMultiplexer> prcManager;

        private static CMultiplexerManager redisManager = null;

        static CMultiplexerManager()
        {
            redisManager = new CMultiplexerManager();
            prcManager = new Dictionary<int, ConnectionMultiplexer>();
        }

        public static CMultiplexerManager GetRedisManager
        {
            get { return redisManager; }
        }

        /// <summary>
        /// 创建链接池管理对象
        /// </summary>
        public static ConnectionMultiplexer CreateManager(int conIndex)
        {
            if(!prcManager.ContainsKey(conIndex))
            {
                prcManager.Add(conIndex, CMultiplexerProvider.GetInstance(conIndex).GetConnection());
            }
            var isSV = prcManager.FirstOrDefault(o => o.Key == conIndex).Value;
            if(isSV.IsConnected)
            {
                return isSV;
            }
            else
            {
                prcManager.Remove(conIndex);
                prcManager.Add(conIndex, CMultiplexerProvider.GetInstance(conIndex).GetConnection());
                return prcManager.FirstOrDefault(o => o.Key == conIndex).Value;
            }
        }

        /// <summary>
        /// 获取连接索引库
        /// </summary>
        /// <param name="conIndex"></param>
        /// <param name="dbIndex"></param>
        /// <returns></returns>
        public IDatabase GetClient(int conIndex,int dbIndex)
        {
            return prcManager.FirstOrDefault(o=>o.Key==conIndex).Value.GetDatabase(dbIndex);
        }
    }
}
